package com.mengxj.jsontojava;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 1，java bean：一个类中，只有成员属性和相应的get，set，hashcode和toString方法
 *
 * json：是前后端交互的一种轻量级数据结构，
 * 对象/map：是以{开头
 * 数组/集合：以[开头
 * 以下均以TestBean1为例
 * 形如：
 * {
 *      "name":"张三",
 *      "address":"长春",
 *      "age": 12,
 * }
 *
 * {
 *      "name":"张三",
 *      "address":"长春",
 *      "age": 12,
 *      "hobby": ["篮球", "跑步"],
 *      "other": {
 *          "school": "xxx小学",
 *          "family": "吉林"
 *      }
 * }
 *
 * json -> bean：会把匹配的属性自动复制，不匹配的默认是所谓的0值
 * 所谓的0值：对象null，int 0  long 0L  boolean false
 *
 * 2，熟悉 数组 <=> 集合 之间的转换
 *
 * @author mengxj
 */
public class JsonToJavaBean {

    public static void main(String[] args) {
        JsonToJavaBean bean = new JsonToJavaBean();
        String bean1Json = bean.beanToJson();
        System.out.println(bean1Json);
        TestBean2 bean1 = bean.jsonToBean(bean1Json);
        System.out.println(bean1.toString());
        List<String> list = new ArrayList<>();
        list.add("q1");
        list.add("q2");
        list.add("q3");
        list.add("q4");
        list.add("q1");
        String[] array = bean.collectionToArray(list);
        System.out.println(Arrays.toString(array));
    }

    private String beanToJson(){
        TestBean1 bean = new TestBean1();
        bean.setName("张三");
        bean.setAddress("长春");
        bean.setAge(12);
        List<String> hobby = new ArrayList<>();
        hobby.add("篮球");
        hobby.add("跑步");
        hobby = Arrays.asList("篮球", "跑步");
        bean.setHobby(hobby);
        return JSON.toJSONString(bean);
    }

    private TestBean2 jsonToBean(String json){
        return JSONObject.parseObject(json, TestBean2.class);
    }

    private String[] collectionToArray(List<String> list){
        int arrLen = list.size();
        String[] resArr = new String[arrLen];
        return list.toArray(resArr);
    }

    private List<String> arrayToCollection(String[] array){
        return Arrays.stream(array).collect(Collectors.toList());
    }
}
